<template>
  <van-list
    v-model="loading"
    :finished="finished"
    finished-text="没有更多了"
    :error.sync="error"
    error-text="加载失败，请点击重试"
    @load="onLoad"
    :immediate-check="false"
  >
    <CommentItem
      v-for="(item, index) in list"
      :key="index"
      :comment="item"
      @update-like="(item.like_count = $event, item.is_liking = !item.is_liking)"
      @reply-click="$emit('reply-click', $event)"
    />
  </van-list>
</template>

<script>
import { getComments } from "@/api/comment";
import CommentItem from "./comment-item.vue";
export default {
  name: "CommentList",
  props: {
    source: {
      type: [String, Number, Object],
      required: true,
    },
    commentList: {
      type: Array,
      default: () => []
    },
    type: {
      type: String,
      validator(val) {
        return ['a', 'c'].includes(val)
      },
      default: 'a'
    }
  },
  components: {
    CommentItem,
  },
  data() {
    return {
      list: this.commentList,
      loading: false,
      finished: false,
      offset: null, // 获取下一页数据的标记 (分页，从哪开始取这页数据)
      limit: 10, // (分页，每页多少条)
      error: false,
    };
  },
  created() {
    this.onLoad();
  },
  methods: {
    async onLoad() {
      // 异步更新数据
      try {
        const { data } = await getComments({
          type: this.type, // 评论类型，a-对文章(article)的评论，c-对评论(comment)的回复
          source: this.source.toString(), // 源id，文章id或评论id (特别注意：需要手动加上toString()，否则会在source的值两边加上双引号，导致id不是一个有效的整形)
          offset: this.offset, // 获取评论数据的偏移量，值为评论id，表示从此id的数据向后取，不传表示从第一页开始读取数据
          limit: this.limit, // 获取的评论数据个数，不传表示采用后端服务设定的默认每页数据量
        });
        this.$emit("onload-success", data.data);
        const { results } = data.data;
        console.log(data);
        this.list.push(...results);
        this.loading = false;
        if (results.length) {
          this.offset = data.data.last_id;
        } else {
          this.finished = true;
        }
      } catch (err) {
        console.log(err);
        this.error = true;
        this.$toast("获取失败");
      }

      // 加载状态结束
      this.loading = false;

      // 数据全部加载完成
      if (this.list.length >= 40) {
        this.finished = true;
      }
    },
  },
};
</script>

<style>
</style>